package cn.bandeqing.pay;

import cn.bandeqing.base.resp.Resp;
import cn.bandeqing.pay.gnete.upbc.bean.BeanMock;
import cn.bandeqing.pay.gnete.upbc.config.OpenApiConfig;
import cn.bandeqing.pay.gnete.upbc.message.MerOpenApiResponse;
import cn.bandeqing.pay.gnete.upbc.utils.PFXUtil;
import com.gnete.api.GneteSignatureAlgorithm;
import com.gnete.api.internal.crypto.GneteSignature;
import com.gnete.upbc.comn.code.rpc.dto.CardNotifyReqDTO;
import com.gnete.upbc.comn.rpc.dto.PaymentRespDTO;
import com.google.gson.reflect.TypeToken;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Type;
import java.security.PublicKey;

@Slf4j
@RestController
@RequestMapping("/payResult")
public class PayResultController {

    @PostMapping("/orderDeposit")
    public void orderDeposit(HttpServletRequest req) {

        try {
            // 接收异步结果通知
            byte[] reqbyte = IOUtils.toByteArray(req.getInputStream());
            if (reqbyte == null) {
                System.out.println("响应信息为空...");
                return;
            }
            String respMsg = new String(reqbyte, OpenApiConfig.charset);
            if (respMsg.length() <= 0) {
                System.out.println("响应信息为空...");
                return;
            }
            System.out.println("respMsg=" + respMsg);

            // 响应报文验签
            int signIndex = respMsg.lastIndexOf("sign") - 2;
            String plainMsg = respMsg.substring(0, signIndex) + "}"; //原文
            String sign = respMsg.substring(signIndex + 9, respMsg.length() - 2); //签名串
            System.out.println("plainMsg=" + plainMsg);
            System.out.println("sign=" + sign);

            // 网关公钥
            PublicKey publicKey = PFXUtil.getPubKeyByPfxByPfx(OpenApiConfig.fileAddr + OpenApiConfig.publicKey);
            String publicKeyHex = Hex.encodeHexString(publicKey.getEncoded());
            boolean verifyResult = GneteSignature.rsaVerify(plainMsg, sign, publicKeyHex, GneteSignatureAlgorithm.RSA2, OpenApiConfig.charset);
            if (!verifyResult) {
                System.out.println("响应报文验签失败...");
                return;
            } else {
                System.out.println("响应报文验签成功...");
            }

            // 解析响应报文
            Type type = new TypeToken<MerOpenApiResponse<PaymentRespDTO<CardNotifyReqDTO>>>() {
            }.getType();
            MerOpenApiResponse<PaymentRespDTO<CardNotifyReqDTO>> gwResp = BeanMock.gson.fromJson(respMsg, type);

            // 业务处理：判断是否需要更新订单结果，推送的结果信息为空或没有支付订单流水号，无需更新结果
            CardNotifyReqDTO result = gwResp.getResponse().getMsgBody();
            String oriMerOrdrNo = result.getOriMerOrdrNo();
            String tradeStatus = result.getTradeStatus();
            String retCode = result.getRetCode();
            String retMsg = result.getRetMsg();
            System.out.println(oriMerOrdrNo + " " + tradeStatus + " " + retCode + " " + retMsg);

            // 原支付订单不存在，无需更新结果

            // 检查原支付订单的处理状态、支付结果-判断是否可根据当前的结果信息更新订单(去重处理)

            // 更新支付信息-置支付成功、交易关闭

        } catch (Exception e) {
            // TODO Auto-generated catch block
//            e.printStackTrace();
            log.error("", e);
        }

    }

}
